package com.gs.order.controller;


import com.gs.common.core.domain.AjaxResult;
import com.gs.common.enums.ExceptionCode;
import com.gs.common.exception.CustomException;
import com.gs.order.service.IOrderService;
import com.gs.order.vo.OrderInfoVo;
import com.gs.order.vo.OrderVo;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

@RestController
public class OrderController {
    @Resource
    private IOrderService iOrderService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 创建订单编号
     * @return
     */
    @RequestMapping("/order/web/orderNum")
    public AjaxResult queryOrderSn() {
        // 创建orderid
        String num = iOrderService.makeOrderId();
        return AjaxResult.success("ok", num);
    }

    /**
     * 生成订单存表
     * @param orderVo
     * @return
     */
    @PostMapping("/order/web/makeOrder")
    public AjaxResult makeOrder(@RequestBody OrderVo orderVo) {

        boolean result = false;
        if (Objects.nonNull(orderVo)) {
            result = iOrderService.isOrderIdOk(orderVo.getOrderNum());
        }
        if (!result) {
            throw new CustomException(ExceptionCode.INVALID_ORDER_ID);
        }
//        Long userId = CommonUtils.getDefaultWebUserId(request);
//        orderVo.setUserId(userId);
        iOrderService.makeOrder(orderVo);
        return AjaxResult.success("订单创建成功");
    }


    /**
     * 获取订单倒计时
     * @param num
     * @return
     */
    @GetMapping("/overTime")
    public AjaxResult overTime(String num) {
        Long overtime =  stringRedisTemplate.getExpire(num+"");
        return AjaxResult.success(overtime);
    }

    /**
     * 取消订单
     * @param num
     * @return
     */
    @GetMapping ("/Cancel")
    public AjaxResult Cancel(String num) {
        System.out.println("111111111"+num);
        iOrderService.updateOrder(4L,num);
        //订单从缓存中删除
        return AjaxResult.success("订单删除成功");
    }


    /**
     * 查询用户订单
     * @param userId
     * @return
     */
    @GetMapping ("FindOrder")
    public AjaxResult FindOrders(Long userId){
        List<OrderInfoVo> gsOrders = iOrderService.findorder(userId);
        return AjaxResult.success(gsOrders);
    }



}
